/**
  @Author: 王炜皓
  @Date: 2023-06-12 19:31:10
  @LastEditTime: 2023-06-13 11:34:16
  @LastEditors: 王炜皓
  @Description: 剖切类
  @FilePath: \cesium-tool\src\views\test\extend\section\section.js
 **/
class Section {
  constructor(option = {}) {
    this._tiles = undefined;
    this._viewer = option.viewer;
    this._radius = undefined;
    this._planeEntity = undefined
    this._offset = {
      cross: 0,
      vertical: 0,
      angle: 0,
    };
  }
  get tiles() {
    return this._tiles;
  }
  set tiles(val) {
    this._tiles = val;
  }
  get offset() {
    return this._offset;
  }
  set offset(val) {
    console.log("setOffset");
    this._offset = val;
  }
  start() {
    if (!this._tiles instanceof Cesium.Cesium3DTileset)
      throw new Error("请先设置剖切的模型");
    let viewer = this._viewer;
    let $this = this;

    var clippingPlanes = (this._tiles.clippingPlanes = this.loadClip());
    var boundingSphere = this._tiles.boundingSphere;
    this._radius = boundingSphere.radius;
    for (var i = 0; i < clippingPlanes.length; ++i) {
      var plane = clippingPlanes.get(i);
      this._planeEntity = viewer.entities.add({
        //添加平面实体 直观裁切面
        id: "裁切面" + i,
        position: boundingSphere.center, // offset, 根据3dtiles同步调整裁切面高度
        plane: {
          dimensions: new Cesium.Cartesian2(150, 150), //(radius * 2.5, radius * 2.5),
          material: Cesium.Color.WHITE.withAlpha(0.0),
          plane: new Cesium.CallbackProperty(
            $this.createPlaneUpdateFunction(plane),
            false
          ),
          outline: true,
          outlineColor: Cesium.Color.WHITE,
        },
      });
    }
  }
  destroy(){
    // this._tiles.clippingPlanes=null
    this._viewer.entities.remove(this._planeEntity)
  }
  createPlaneUpdateFunction(plane) {
    let $this = this;
    return function () {
      console.log(plane, "plane");
      let of = $this._offset;
      plane.distance = calcdistance(of.distance);
      plane.normal = new Cesium.Cartesian3(
        calc(of.vertical),
        calc(of.angle),
        calc(of.cross)
      );
      return plane;
    };
    function calc(val) {
      return (50 - val) / 50;
    }
    function calcdistance(val) {
      return $this._radius * 1.5*((50 - val) / 50);
    }
  }

  loadClip() {
    let clippingPlanes = new Cesium.ClippingPlaneCollection({
      planes: [new Cesium.ClippingPlane(new Cesium.Cartesian3(1.0, 0.0, 0), 0)],
      edgeColor: Cesium.Color.RED,
      edgeWidth: 1.0,
      unionClippingRegions: true, //true 才能多个切割
    });
    return clippingPlanes;
  }
}
export default Section;
